package com.ruoyi.system.chaincode.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.chaincode.config.HyperLedgerFabricProperties;
import lombok.AllArgsConstructor;
import org.checkerframework.checker.units.qual.A;
import org.hyperledger.fabric.client.Contract;
import org.hyperledger.fabric.client.Gateway;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/fabric")
@AllArgsConstructor
public class FabricController extends BaseController {


    @Resource
    private FabricService service;

    @PostMapping("/register/user")
    public AjaxResult registerUser(@RequestBody SysUser user) {
        return toAjax(service.registerUser(user));
    }











    final Gateway gateway;

    final Contract contract;

    final HyperLedgerFabricProperties hyperLedgerFabricProperties;

    /**
     * 注册用户
     */
    @PostMapping("/register")
    public String registerUser(@RequestBody ChainAsset user) {
        if(null == user.getAssetKey()) return "Error: User ID cannot be empty";
        try {
            byte[] registerUsers = contract.submitTransaction("register", JSON.toJSONString(user));
            String s = new String(registerUsers, StandardCharsets.UTF_8);
            ChainData chainData = JSON.parseObject(new String(registerUsers, StandardCharsets.UTF_8), ChainData.class);

            if(chainData.getCode().equals("200")) {

                return s;
            } else {
                return "Error: " + chainData.getMsg();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }


    /**
     * 获取
     */
    @GetMapping("/info")
    public String getAsset(@RequestParam String assetKey, String txId) {
        String cxt = "getAsset";
        try {
            byte[] bytes = contract.evaluateTransaction(cxt, assetKey, txId);
            String s = new String(bytes, StandardCharsets.UTF_8);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    /**
     * 获取历史
     */
    @GetMapping("/history")
    public String getAsset(@RequestParam String assetKey) {
        String cxt = "getAsset";
        try {
            byte[] bytes = contract.evaluateTransaction(cxt, assetKey, "null");
            String s = new String(bytes, StandardCharsets.UTF_8);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }



    /// /////////////////////////////////////////////////////////


    /**
     * 农产品上链
     */
    @PostMapping("/uplink")
    public String uplink(@RequestParam("userID") String userID, @RequestParam("traceability_code") String traceability_code,
                         @RequestParam("arg1") String arg1, @RequestParam("arg2") String arg2,
                         @RequestParam("arg3") String arg3, @RequestParam("arg4") String arg4,
                         @RequestParam("arg5") String arg5) {
        try {
            // 先检查用户是否存在
            try {
                contract.evaluateTransaction("getUserInfo", userID);
            } catch (Exception e) {
                return "Error: User does not exist. Please register the user first. Details: " + e.getMessage();
            }
            byte[] result = contract.submitTransaction("uplink", userID, traceability_code, arg1, arg2, arg3, arg4, arg5);
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    /**
     * 获取用户的农产品列表
     */
    @GetMapping("/getFruitList")
    public String getFruitList(@RequestParam("userID") String userID) {
        try {

            byte[] result = contract.evaluateTransaction("getFruitList", userID);
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    /**
     * 获取所有农产品信息
     */
    @GetMapping("/getAllFruitInfo")
    public String getAllFruitInfo() {
        try {

            byte[] result = contract.evaluateTransaction("getAllFruitInfo");
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    /**
     * 获取农产品上链历史
     */
    @GetMapping("/getFruitHistory")
    public String getFruitHistory(@RequestParam("traceability_code") String traceability_code) {
        try {

            byte[] result = contract.evaluateTransaction("getFruitHistory", traceability_code);
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

}
